package gz;

import com.fasterxml.jackson.databind.ObjectMapper;
import enums.TypeApply;
import enums.TypeContinue;
import enums.TypeCost;
import enums.TypeLaw;
import enums.TypeStatus;
import model.Annex;
import model.Works;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.NumberToTextConverter;
import utils.HttpClientUtils;

import java.io.File;
import java.io.FileInputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

public class Standard {


    public static void main(String[] args) {

        try {
            // 创建一个文件输入流对象
            FileInputStream file = new FileInputStream(new File("D:\\aaa.xlsx"));

            // 根据文件输入流对象创建一个工作簿对象
            Workbook workbook = WorkbookFactory.create(file);

            // 获取第一个工作表
            Sheet sheet = workbook.getSheetAt(0);
            HashMap<String, Object> map = new HashMap<>();
            List<Works> works = new ArrayList<>();
            map.put("awardsId", 71);
            map.put("status", 2);
            map.put("nodeId", "339");
            map.put("worksId", null);

            // 迭代工作表的每一行
            Iterator<Row> rowIterator = sheet.iterator();
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Works work = new Works();
                work.setApply_centers("65");
                // 迭代每一行的每一列
//                Iterator<Cell> cellIterator = row.cellIterator();
                System.out.println(getCellValueAsString(row.getCell(0)));
                //申请号
                String works_zlh = getCellValueAsString(row.getCell(1));
                work.setWorks_zlh(works_zlh);
                //申请日
                String cellValue2 = getCellValueAsString(row.getCell(2));
                String first_date_slrq = formatDate(cellValue2);
                work.setFirst_date_slrq(first_date_slrq);
                //发明名称
                String works_title = getCellValueAsString(row.getCell(3));
                work.setWorks_title(works_title);
                //交底书名称
                String works_title_nsqmc = getCellValueAsString(row.getCell(4));
                work.setWorks_title_nsqmc(works_title_nsqmc);
                //代理编号
                String works_ddfbh = getCellValueAsString(row.getCell(5));
                work.setWorks_ddfbh(works_ddfbh);
                //公告号/公开号
                String works_ggh = getCellValueAsString(row.getCell(6));
                work.setWorks_ggh(works_ggh);
                //公告日/公开日
                String cellValue7 = getCellValueAsString(row.getCell(7));
                String first_date_ggr = formatDate(cellValue7);
                work.setFirst_date_ggr(first_date_ggr);
                //授权日
                String cellValue8 = getCellValueAsString(row.getCell(8));
                String first_date = formatDate(cellValue8);
                work.setFirst_date(first_date);
                //发明人
                String cellValue9 = getCellValueAsString(row.getCell(9));
                List<Annex> annex = getAnnex(cellValue9);
                work.setWorks_author(annex);
                //申请人
                String cellValue10 = getCellValueAsString(row.getCell(10));
                List<String> company = getCompany(cellValue10);
                if (CollectionUtils.isNotEmpty(company)) {
                    work.setWorks_zsqdw(company.get(0));
                    if (company.size() > 1) {
                        StringBuilder builder = new StringBuilder();
                        for (int i = 1; i < company.size(); i++) {
                            builder.append(company.get(i));
                        }
                        work.setWorks_gtsqdw(builder.toString());
                    }
                }
                //法律状态
                String awards_stage_id = getCellValueAsString(row.getCell(11));
                getLawType(awards_stage_id, work);
                //专利类型
                String cellValue12 = getCellValueAsString(row.getCell(12));
                String work_type = getWorkType(cellValue12);
                work.setWorks_type(work_type);
                //联系人
                String works_lxr = getCellValueAsString(row.getCell(13));
                work.setWorks_lxr(works_lxr);
                //代理机构
                String works_dlfgs = getCellValueAsString(row.getCell(14));
                work.setWorks_dlfgs(works_dlfgs);
                //申请方式
                String cellValue15 = getCellValueAsString(row.getCell(15));
                String apply_channel = getApplyType(cellValue15);
                work.setApply_channel(apply_channel);
                //缴费单位
                String works_jfdw = getCellValueAsString(row.getCell(16));
                work.setWorks_jfdw(works_jfdw);
                //来源于技术项目
                String works_yzyjsxm = getCellValueAsString(row.getCell(17));
                work.setWorks_yzyjsxm(works_yzyjsxm);
                //目前应用于技术环节
                String apply_link = getCellValueAsString(row.getCell(18));
                work.setApply_link(apply_link);
                //是否继续维持
                String cellValue19 = getCellValueAsString(row.getCell(19));
                String continue_maintain = getContinueType(cellValue19);
                work.setContinue_maintain(continue_maintain);
                works.add(work);
            }
            // 关闭文件流
            file.close();
            for (Works work : works) {
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    map.put("works", work);
                    String jsonStr = objectMapper.writeValueAsString(map);
                    System.out.println("jsonStr:" + jsonStr);
                    String s = HttpClientUtils.sendPostRequest("http://localhost:8000/api/design/declareWorks", "Idea-94d80bb7=f0cc6c79-84bb-4f09-b63b-10742e8c97fb;SESSION=NmU2Njc0OWMtYWI2ZS00ZTdlLTg1ZmEtNmE1Nzg0YTRiZTA4", jsonStr);
                    System.out.println(work.getWorks_title() + "申报返回结果：" + s);
//                    return;
                } catch (Exception e) {
                    System.out.println("作品申报失败，失败作品：" + work.getWorks_title());
                    throw new RuntimeException(e);
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void getLawType(String cellValue11, Works works) {
        if (StringUtils.isNotBlank(cellValue11)) {
            if (cellValue11.contains("未缴")) {
                works.setAwards_stage_id(TypeLaw.B.code);
                works.setCost_status_id(TypeCost.WAIT.code);
            } else if (cellValue11.contains("届满") || cellValue11.contains("失效")) {
                works.setAwards_stage_id(TypeLaw.I.code);
                works.setCost_status_id(TypeCost.OVERDUE.code);
            } else if (cellValue11.contains("授权")) {
                works.setAwards_stage_id(TypeLaw.F.code);
                works.setCost_status_id(TypeCost.RUN.code);
            } else if (cellValue11.contains("放弃续费")) {
                works.setAwards_stage_id(TypeLaw.H.code);
                works.setCost_status_id(TypeCost.STOP.code);
            } else if (cellValue11.contains("驳回")) {
                works.setAwards_stage_id(TypeLaw.G.code);
            } else if (cellValue11.contains("实质审查") || cellValue11.contains("实审")) {
                works.setAwards_stage_id(TypeLaw.E.code);
            } else if (cellValue11.contains("发明初合") || cellValue11.contains("初合") || cellValue11.contains("初审合格")) {
                works.setAwards_stage_id(TypeLaw.D.code);
            }

        }

    }

    // 将单元格内容转换为字符串类型
    private static String getCellValueAsString(Cell cell) {
        String cellValue = "";

        // 根据单元格类型获取内容
        switch (cell.getCellType()) {
            case STRING:
                cellValue = cell.getStringCellValue();
                break;
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    cellValue = cell.getDateCellValue().toString();
                } else {
                    String value= NumberToTextConverter.toText(cell.getNumericCellValue());
//                    double value = cell.getNumericCellValue();
                    cellValue = value;
                }
                break;
            case BOOLEAN:
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA:
                cellValue = cell.getCellFormula();
                break;
            case BLANK:
                cellValue = "";
                break;
            default:
                cellValue = "";
        }

        return cellValue;
    }

    private static String formatDate(String str) {
        if (StringUtils.isNotBlank(str)) {
            String dateString = str.trim();
            if (dateString.contains("-")) {
                if (dateString.length() == 10) {
                    return dateString;
                } else {
                    String[] strings = dateString.split("-");
                    if (strings[1].length() < 2) {
                        strings[1] = "0" + strings[1];
                    }
                    if (strings[2].length() < 2) {
                        strings[2] = "0" + strings[2];
                    }
                    return strings[0] + "-" + strings[1] + "-" + strings[2];
                }
            } else if (dateString.contains("日")) {
                String[] years = dateString.split("年");
                String[] months = years[1].split("月");
                String[] days = months[1].split("日");
                String date = formatDate(years[0], "0") + "-" + formatDate(months[0], "0") + "-" + formatDate(days[0], "0");
                return date;
            } else if (dateString.contains("年")) {
                String[] years = dateString.split("年");
                String[] months = years[1].split("月");
                String date = formatDate(years[0], "0") + "-" + formatDate(months[0], "0") + "-" + formatDate(months[1], "0");
                return date;
            } else {
                try {
                    SimpleDateFormat sourceFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
                    sourceFormat.setTimeZone(TimeZone.getTimeZone("CST"));
                    Date date = sourceFormat.parse(dateString);
                    SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd");
                    return targetFormat.format(date);
                } catch (ParseException e) {
                    System.out.println("error：" + str);
                    return null;
                }
            }
        }
        return null;

    }

    private static String formatDate(String str, String format) {
        if (str.length() > 1) {
            return str;
        } else {
            return format + str;
        }
    }

    private static String getWorkType(String str) {
        if (StringUtils.isNotBlank(str)) {
            if (str.contains("发明")) {
                return TypeStatus.CREATE.code;
            } else if (str.contains("实用新型")) {
                return TypeStatus.NEW.code;
            } else {
                return TypeStatus.DESIGN.code;
            }
        }
        return null;
    }

    private static List<Annex> getAnnex(String author) {
        if (StringUtils.isNotBlank(author)) {
            List<Annex> annexes = new ArrayList<>();
            Annex annex = new Annex();
            annex.setUid("311");
            annex.setIndex(1);
            annex.setItem1(author);
            annexes.add(annex);
            return annexes;
        }
        return null;
    }

    private static List<String> getCompany(String company) {
        List<String> strings = new ArrayList<>();
        if (StringUtils.isNotBlank(company)) {
            if (company.contains("|")) {
                strings = Arrays.asList(company.split("|"));
            } else if (company.contains("；")) {
                strings = Arrays.asList(company.split("；"));
            } else if (company.contains("、")) {
                strings = Arrays.asList(company.split("、"));
            } else {
                strings.add(company);
            }
            return strings;
        }
        return null;
    }

    private static String getApplyType(String str) {
        if (StringUtils.isNotBlank(str)) {
            if (str.contains("普通申请")) {
                return TypeApply.NORMAL.code;
            } else if (str.contains("优先")) {
                return TypeApply.EXCELLENT.code;
            } else {
                return TypeApply.FAST.code;
            }
        }
        return null;
    }

    private static String getContinueType(String str) {
        if (StringUtils.isNotBlank(str)) {
            if (str.contains("是")) {
                return TypeContinue.YES.code;
            } else if (str.contains("否")) {
                return TypeContinue.NO.code;
            }
        }
        return null;
    }

}
